package com.tn.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
public class TcpNettyServer implements CommandLineRunner{

    @Value("${socket.port:8982}")
    private int cardMachinePort;

    @Value("${project.startup.mptest: }")
    private String mptest;

    @Resource
    private CardMachineHandle cardMachineHandle;

//    @PostConstruct
    public void run(String... args) throws Exception {
        if(mptest.equalsIgnoreCase("test")) {
            return;
        }
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
    //                        socketChannel.pipeline().addLast(new Jt808NettyEncoder(coder));
    //                        socketChannel.pipeline().addLast(new Jt808NettyDecoder(coder, bufferWrapper));
                            socketChannel.pipeline().addLast(cardMachineHandle);  // 发卡机处理
//                            log.info("{} +++++ 已连接", socketChannel.remoteAddress().getAddress().getHostAddress());
                        }
                    });
            log.info("=== 绑定创建 {}===", cardMachinePort);
            ChannelFuture channelFuture1 = serverBootstrap.bind(cardMachinePort).sync(); // 服务器异步创建绑定
            log.info("=== 启动完毕！！===");
            channelFuture1.channel().closeFuture().sync(); // 关闭服务器通道
            log.info("=== closeFuture() 关闭服务器通道！！===");

        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.error("({}) 发生异常：",cardMachinePort, e);
        } finally {
            log.error("({}) 服务关闭", cardMachinePort );
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
